<template>
  <UForm class="relative space-y-5 my-5" :schema="schema" :state="state" @submit="handleSubmit">
    <UFormField required label="人员名称" name="name">
      <UInput placeholder="请输入人员名称" v-model="state.name" />
    </UFormField>
    <UFormField label="手机号码" name="phone">
      <UInput placeholder="请输入人员手机号码" v-model="state.phone" />
    </UFormField>
    <UFormField label="人员角色" name="role">
      <SelectRemote url="/api/role/list" v-model="state.role"></SelectRemote>
    </UFormField>
    <UFormField label="人员状态" name="status">
      <USelect
        :items="enumToOptions(StatusEnum)"
        :ui="{ base: 'w-full' }"
        placeholder="请选择"
        v-model="state.status"
      />
    </UFormField>
    <UButton :loading="submiting" type="submit" icon="i-mingcute:file-check-line"> 提交 </UButton>
  </UForm>
</template>

<script setup lang="ts">
import { object, string } from 'zod'
import type { UserParam } from '~~/shared/types/user'

const toast = useToast()

const { params } = useRoute()

const useForm = () => {
  const FORM_PARAMS: UserParam = {
    phone: '',
    role: '',
    name: '',
    status: StatusEnum.可用,
    id: 0
  }

  const schema = object({
    name: string('请输入人员名称'),
    role: string('请选择权限'),
    phone: string('请输入手机号码').regex(/^1[3-9]\d{9}$/, '请输入正确的手机号码')
  })

  const state = ref<UserParam>({ ...FORM_PARAMS })

  const submiting = ref(false)

  async function handleSubmit() {
    submiting.value = true
    try {
      toast.add({
        title: '编辑用户',
        icon: 'i-svg-spinners:clock',
        description: '保存成功'
      })
    } finally {
      submiting.value = false
    }
  }

  return {
    schema,
    submiting,
    state,
    handleSubmit
  }
}

const { schema, submiting, state, handleSubmit } = useForm()

useHead({
  title: '编辑用户'
})
</script>
